import { WebSocketServer, WebSocket } from 'ws';
import http from 'http'
import mysql from 'mysql2'
import { WebSocketData } from './DataStrcutures.js'
import { CheckToken, CreateToken } from './Token.js'
import MessageService from '../service/messageService/messageService.js'



/**
 * 用于维持在线用户表
 * @type {Map<string,WebSocket>}
 */
let socketList = new Map()
/**
 * 创建服务，挂载到http服务上
 * @param {http.Server} server 
 */
function _initWebSocket(server) {
    const socketServer = new WebSocketServer({ server, path: '/socket', });

    socketServer.on('connection', function (socket, request) {
        socket.on('open', function (...arg) {
            console.log(arg);
        })
        socket.on('message', async function (data, isBinary) {
            try {
                /**
                 * @type {WebSocketData}
                 */
                // let request = JSON.parse(decodeURIComponent(escape(data)))
                let request = JSON.parse(data)
                let token = request.headers.authorization.split(' ')[1]
                let { status } = await CheckToken(token)
                if (status) {
                    if (request.headers._initInfo) {
                        // 初始化信息,空数据
                        socketList.set(request.headers.userID, this)
                    }
                    else {
                        // 普通信息
                        if (request.headers.sendID) {
                            if (request.headers.receiverID) {
                                // 根据用户ID获取socket连接
                                socketList.set(request.headers.sendID, this)
                                let receiver = socketList.get(request.headers.receiverID)
                                // 判断接收方连接
                                if (receiver && receiver.readyState == WebSocket.OPEN) {
                                    const status = await MessageService.InsertMessage({
                                        sendID: request.headers.sendID,
                                        receiverID: request.headers.receiverID,
                                        messageContent: request.data.msg,
                                        messageType: 1
                                    })
                                    if (status) {
                                        let response = request
                                        receiver.send(JSON.stringify(response))
                                        this.send(JSON.stringify(response))
                                    }
                                    else {
                                        // 信息保存失败
                                        throw Error('信息发送失败，没有保存信息')
                                    }
                                }
                                else {
                                    // 接收人连接不存在，先保存，信息为未读
                                    const status = await MessageService.InsertMessage({
                                        sendID: request.headers.sendID,
                                        receiverID: request.headers.receiverID,
                                        messageContent: request.data.msg,
                                        messageType: 0
                                    })
                                    if (status) {
                                        // 返回发送成功码
                                        let response = request
                                        this.send(JSON.stringify(response))
                                    }
                                    else {
                                        // 信息保存失败
                                        // 返回发送失败码
                                        throw Error('信息发送失败，没有保存信息')
                                    }
                                }
                            }
                            else {
                                // 没有接收人ID
                                throw TypeError('没有receiverID')
                            }
                        }
                        else {
                            // 没有发送人ID
                            throw TypeError('没有sendID')
                        }
                    }
                }
                else {
                    // 返回token过期的信息
                }
            } catch (error) {
                // 统一处理报错信息
                this.send(JSON.stringify(request))
                console.error(error);
            }
        })
        socket.on('close', (code, reason) => {

        })
    });
    socketServer.on('close', (...arg) => {
        console.log(arg);
    })
    socketServer.addListener('error', (err, ...arg) => {
        console.log(err, arg);
    })
}

export default _initWebSocket